package com.ali.ttt.webSocket.cluster;

import com.ali.ttt.webSocket.domain.SessionMap;
import com.alibaba.fastjson.JSONObject;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.serializer.RedisSerializer;

import javax.annotation.Resource;

/**
 * @Author : yuxl
 * @create 2024/7/15 1:21 PM
 */
@Slf4j
@Component
public class NettyRedisMessageListener implements MessageListener {

    public static String topic = "netty.onMessage";

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        //需要在加载bean的时候配置相同的redis序列化器，否则会乱码
        RedisSerializer<String> keySerializer = RedisSerializer.string();
        RedisSerializer valueSerializer = RedisSerializer.java();
        log.info("----------接收到发布者消息----------");
        log.info("|频道:{}", keySerializer.deserialize(message.getChannel()));
        log.info("|当前监听器绑定的pattern:{}", new String(pattern));
        log.info("|消息内容:{}", valueSerializer.deserialize(message.getBody()));
        log.info("---------------------------------");
        Object deserialize = valueSerializer.deserialize(message.getBody());
        SessionMap.inst().getMap().forEach((k, v)->{
            v.getChannel().writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(deserialize.toString())));
        });
    }

    public void pushMessage(String sessionId,String msg){
        redisTemplate.convertAndSend(topic+"."+sessionId, msg);
    }

    public void pushMessage(String msg){
        redisTemplate.convertAndSend(topic, msg);
    }
}
